package yxy.cherry.paycenter.channelmodule.sdk_oppo_quick;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import yxy.apple.logger.Logger;
import yxy.apple.util.MD5Utility;
import yxy.apple.util.SdkUtil;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.PayMoudle_channel;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.util.HttpHelper;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannelDAO;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.bean.order.OrderInfo;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

//客户端下单（创建订单）
public class PayMoudle_oppo_quick extends PayMoudle_channel {
	static final Logger logger = Logger.create(PayMoudle_oppo_quick.class);

	@Override
	public String getChannel() {
		return SdkChannel.sdk_oppo_quick;
	}
	@Override
	public JSONObject dealPay(JSONObject infoobj) {
		// TODO Auto-generated method stub
		return null;
	}

	//构造订单信息，生成签名，返回给客户端
	@Override
	public JSONObject createOrderInfo(JSONObject infoobj, orders o) throws Exception {
		JSONObject extObj = JSONObject.parseObject(infoobj.getString("ext")); //扩展参数
		String openId = extObj.getString("openId"); //登录用户token（oppo方）
		String appId = extObj.getString("appId");
		String engineVersion = extObj.getString("engineVersion");
		long timestamp = System.currentTimeMillis();
		//读取渠道配置
		SDK_UnionChannel unionChannel = SDK_UnionChannelDAO.getByAppId(SdkChannel.sdk_oppo_quick, appId);
		//渠道方下单
		TreeMap<String, String> treeMap = new TreeMap<>();
		treeMap.put("appId", appId);
		treeMap.put("openId", openId);
		treeMap.put("timestamp", String.valueOf(timestamp));
		treeMap.put("productName", o.getGoodsname());
		treeMap.put("productDesc", o.getGoodsname());
		treeMap.put("count", "1");
		treeMap.put("price", String.valueOf(o.getGoodsprice())); //分
		treeMap.put("currency", "CNY");
		treeMap.put("attach", appId); //附加信息
		treeMap.put("callBackUrl", "");
		treeMap.put("cpOrderId", o.getMyorderid());
		treeMap.put("appVersion", "1.0.0");
		treeMap.put("engineVersion", engineVersion);
		String content = SdkUtil.treeMapToContent(treeMap, true);
		String sign = sign(content, unionChannel.getPrivateKey());
		treeMap.put("sign", sign);

		JSONObject params = JSONObject.parseObject(JSON.toJSONString(treeMap));
		String url = "https://jits.open.oppomobile.com/jitsopen/api/pay/v1.0/preOrder";
		String res = HttpHelper.doPost(url, HttpHelper.getValuePair(params), 30000); //
		logger.info(SdkChannel.sdk_oppo_quick + ":preOrder:" + res);
		JSONObject resobj = JSONObject.parseObject(res);
		if (!resobj.getString("errCode").equals("200")) throw new Exception(resobj.getString("errMsg"));
		JSONObject data = resobj.getJSONObject("data");


		//构造数据，返回给客户端
		JSONObject json = new JSONObject();
		TreeMap<String, String> infoMap = new TreeMap<>();
		infoMap.put("appKey", unionChannel.getAppKey());
		infoMap.put("orderNo", data.getString("orderNo"));
		infoMap.put("timestamp", String.valueOf(timestamp));
		content = SdkUtil.mapToContent(infoMap, true);
		sign = sign(content, unionChannel.getPrivateKey());
		infoMap.remove("appKey");
		infoMap.put("appId", appId);
		infoMap.put("token", openId);
		infoMap.put("paySign", sign);
		json.put("orderInfo", infoMap);
		logger.info(SdkChannel.sdk_oppo_quick + ":createOrderInfo : %s", JSON.toJSON(json));
		
		return json;
	}

	//创建订单
	public orders createOrderOPPOQUICK(int dataid, String playercode, int serverid, int acttype) {
		orders o = createOrder(getChannel(), dataid, acttype, playercode, serverid);
		addOrder(o);
		return o;
	}
	
	/**
	 * 创建 OrderInfo
	 * @param o
	 * @param curs
	 * @param c
	 * @param payamount
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, charge c, int payamount) {
		createOrderInfoModule(o, curs, c.getVipexp(), payamount);
	}
	
	/**
	 * 
	 * @param o
	 * @param curs
	 * @param vipexp
	 * @return
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, int vipexp, int payamount) {
		OrderInfo oi = OrderInfoModule.createOrderInfo(o.getGoodsid(), o.getChannel(), o.getMyorderid(), new DateTime(o.getCreatetime().getTime()), 
				OrderInfoModule.orderinforuning, o.getPlatorderid(), o.getActtype(), o.getPlayercode(), curs, 
				o.getServerid(), DateTime.now(), vipexp, payamount, o.getGoodsprice());
		logger.info("createOrderInfoModule %s", JSON.toJSONString(oi));
		OrderInfo.set(o.getPlayercode(), oi);
	}

	public static String sign(String content, String privateKey) {
		if (null == content) {
			return null;
		}
		//使用加密算法规则
		String SIGN_ALGORITHMS = "SHA256WithRSA";
		String charset = "UTF-8";
		try {
			//Base64请采用服务器端标准的Base64算法库。
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes(charset));
			byte[] signed = signature.sign();
			//Base64请采用服务器端标准的Base64算法库。
			return Base64.encodeBase64String (signed);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return null;
	}
}
